package com.system.cipher;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import com.sun.crypto.provider.SunJCE;

public class TripleDES {
	private static final String DEFAULT_CRYPT_ALGORITHM = "DESede/CBC/PKCS5Padding";
	private static final String DEFAULT_KEY_ALGORITHM = "DESede";
	private static final byte[] DEFAULT_IV = new byte[] { 1, 2, 3, 4, 5, 6, 7,
			8 };

	static {
		Security.addProvider(new SunJCE());
	}

	private static Key KeyGenerator(String KeyStr)
			throws GeneralSecurityException {
		byte[] input = HEX.decode(KeyStr);
		DESedeKeySpec KeySpec = new DESedeKeySpec(input);
		SecretKeyFactory KeyFactory = SecretKeyFactory
				.getInstance(DEFAULT_KEY_ALGORITHM);
		return KeyFactory.generateSecret(KeySpec);
	}

	public static byte[] encrypt(byte[] input, String strKey,
			String cryptAlgorithm, byte[] byteIV)
			throws UnsupportedEncodingException, GeneralSecurityException {
		Key k = KeyGenerator(strKey);
		IvParameterSpec IVSpec = new IvParameterSpec(byteIV);
		Cipher cipher = Cipher.getInstance(cryptAlgorithm);
		cipher.init(Cipher.ENCRYPT_MODE, k, IVSpec);
		return cipher.doFinal(input);
	}

	public static byte[] decrypt(byte[] input, String strKey,
			String cryptAlgorithm, byte[] byteIV)
			throws UnsupportedEncodingException, GeneralSecurityException {
		Key k = KeyGenerator(strKey);
		IvParameterSpec IVSpec = new IvParameterSpec(byteIV);
		Cipher cipher = Cipher.getInstance(cryptAlgorithm);
		cipher.init(Cipher.DECRYPT_MODE, k, IVSpec);
		return cipher.doFinal(input);
	}

	public static byte[] encrypt(byte[] input, String strKey)
			throws UnsupportedEncodingException, GeneralSecurityException {
		return encrypt(input, strKey, DEFAULT_CRYPT_ALGORITHM, DEFAULT_IV);
	}

	public static byte[] decrypt(byte[] input, String strKey)
			throws UnsupportedEncodingException, GeneralSecurityException {
		return decrypt(input, strKey, DEFAULT_CRYPT_ALGORITHM, DEFAULT_IV);
	}
	public static void main(String[] args) throws Exception {
		Key key =KeyGenerator("cfyking");
		key.toString();
		String value ="dfdfdfdfd";
		byte[] encryptValue=encrypt(value.getBytes(), key.toString());
		byte[] decryptValue=decrypt(encryptValue, key.toString());
		System.out.println(new String(decryptValue));
		
	}
}
